/********************************************************************************
 *      Copyright:  (C) 2024 LiYi<1751425323@qq.com>
 *                  All rights reserved.
 *
 *       Filename:  mos_connect.c
 *    Description:  This file 
 *
 *        Version:  1.0.0(30/04/24)
 *         Author:  LiYi <1751425323@qq.com>
 *      ChangeLog:  1, Release initial version on "30/04/24 20:37:06"
 *                 
 *******************************************************************************/
#include <stdio.h>
#include <time.h>
#include <string.h>
#include <errno.h>
#include <mosquitto.h>
#include "mosconnect.h"
#include "packet.h"
#include "cJSON.h"
#include "logger.h"

int initialize_mosquitto (struct mosquitto **mosq, mqtt_report_t *mqtt)
 {
	 int		rv;
	 int		loop;

	 rv = mosquitto_lib_init();
	 if( rv != MOSQ_ERR_SUCCESS )
	 {
		 log_error("Mosq_Connect() failed: %s", strerror(errno) );
		 mosquitto_lib_cleanup() ;	
		 return -1;
	 }

	 printf("ini success\n");

	 /*  create a new client instance */
	 *mosq = mosquitto_new(mqtt->clientid, mqtt->session, NULL) ;
	 if(!mosq)
	 {
		 log_error("new pub_test failure:%s",strerror(errno));
		 rv = -2;
		 goto cleanup;
	 }

	 log_debug("Create mosquitto client sucessfully!");

	 rv = mosquitto_username_pw_set(*mosq,mqtt->username,mqtt->passwd);
	 if(rv != MOSQ_ERR_SUCCESS)
	 {
		 log_error("set username and password failure:%s",strerror(errno));
		 rv = -3;
		 goto cleanup;
	 }

	 rv = mosquitto_connect(*mosq, mqtt->hostname, mqtt->port, mqtt->keep_alive_interval);

	 if( rv != MOSQ_ERR_SUCCESS )
	 {
		 fprintf(stderr, "Error Connect: %s\n", mosquitto_strerror(rv));  
		 log_error("Mosq_Connect() failed: %s", strerror(errno) );
		 rv = -4;
		 goto cleanup;
	 }

	 printf("Connect %s:%d Sucessfully!", mqtt->hostname, mqtt->port);

	 loop = mosquitto_loop_start(*mosq);
	 if(loop != MOSQ_ERR_SUCCESS)
	 {
		 log_error("mosquitto loop error!");
		 rv = -5;
		 //销毁线程
		 mosquitto_loop_stop(*mosq, true);
		 goto cleanup;
	 }

	 return 0;

cleanup:
	 mosquitto_destroy(*mosq);
	 mosquitto_lib_cleanup();
	 return rv;

 } 

